<?php
/***
* Class: Session
* File: Session.php
* @author Nguyen Nhu Khang - nhukhang095@gmail.com
* @copyright 4e Web Development Groups
*/
class Session{

    /**
    * Initializes session data
    *
    * Create a session (or resumes the current one based on
    * the session id being passed via a GET variable or a cookie)
    */
    function create($name = 'SessionID', $id = null){
        Session::name($name);
        if (is_null(Session::_detectID())){
            Session::id($id ? $id : md5(uniqid(dechex(rand())).$_SERVER['REMOTE_ADDR']));
        }
        session_start();
        if (!isset($_SESSION['__HTTP_Session_Info'])) {
            $_SESSION['__HTTP_Session_Info'] = HTTP_SESSION_STARTED;
        }else{
            $_SESSION['__HTTP_Session_Info'] = HTTP_SESSION_CONTINUED;
        }
    }

    /**
    * Writes session data and end session
    */
    function pause()
    {
        session_write_close();
    }

    function destroy(){
        session_unset();
        session_destroy();
        // set session handlers again to avoid fatal error in case HTTP_Session::start() will be called afterwards
        if (isset($GLOBALS['HTTP_Session_Container']) && is_a($GLOBALS['HTTP_Session_Container'], 'HTTP_Session_Container')) {
            $GLOBALS['HTTP_Session_Container']->set();
        }
    }

    function clear(){
        $info = $_SESSION['__HTTP_Session_Info'];
        session_unset();
        $_SESSION['__HTTP_Session_Info'];
    }

    function name($name = null){
        return isset($name) ? session_name($name) : session_name();
    }

    function id($id = null){
        return isset($id) ? session_id($id) : session_id();
    }

    function setExpire($time, $add = true){
        if ($add){
            if (!isset($_SESSION['__HTTP_Session_Expire_TS'])) {
                  $_SESSION['__HTTP_Session_Expire_TS'] = time() + $time;
            }
            // update session.gc_maxlifetime
            $currentGcMaxLifetime = Session::setGcMaxLifetime(null);
            Session::setGcMaxLifetime($currentGcMaxLifetime + $time);
        } elseif (!isset($_SESSION['__HTTP_Session_Expire_TS'])) {
            $_SESSION['__HTTP_Session_Expire_TS'] = $time;
        }
    }

    function setIdle($time){
        $_SESSION['__HTTP_Session_Idle'] = $time;
    }

    function sessionValidThru(){
        if (!isset($_SESSION['__HTTP_Session_Idle_TS']) || !isset($GLOBALS['__HTTP_Session_Idle'])) {
            return 0;
        }else{
            return $_SESSION['__HTTP_Session_Idle_TS'] + $_SESSION['__HTTP_Session_Idle'];
        }
    }

    function isExpired(){
        if (isset($_SESSION['__HTTP_Session_Expire_TS']) && $_SESSION['__HTTP_Session_Expire_TS'] < time()) {
            return true;
        } else {
            return false;
        }
    }

    function isIdle(){
        if (isset($_SESSION['__HTTP_Session_Idle_TS']) && (($_SESSION['__HTTP_Session_Idle_TS'] + $_SESSION['__HTTP_Session_Idle']) < time())) {
            return true;
        } else {
            return false;
        }
    }

    function updateIdle(){
        $_SESSION['__HTTP_Session_Idle_TS'] = time();
    }

    function useCookies($useCookies = null){
        $res = ini_get('session.use_cookies') ? true : false;
        if (isset($useCookies)){
            ini_set('session.use_cookies', $useCookies ? 1 : 0);
        }
        return $res;
    }

    function isNew(){
        return !isset($_SESSION['__HTTP_Session_Info']) ||
            $_SESSION['__HTTP_Session_Info'] == HTTP_SESSION_STARTED;
    }

    function register($name){
        session_register($name);
    }

    function unregister($name){
        session_unregister($name);
    }

    function get($name, $default = null){
         if (!isset($_SESSION[$name]) && isset($default)) {
            $_SESSION[$name] = $default;
         }
         return isset($_SESSION[$name]) ? $_SESSION[$name] : null;
    }

    function set($name, $value){
       $old = isset($_SESSION[$name]) ?  $_SESSION[$name] : null;
       if (null === $value) {
           unset($_SESSION[$name]);
       } else {           
           $_SESSION[$name] = $value;           
       }
       return $old;
    }


    function &getLocal($name, $default){
        $local = md5(Session::localName());
        if (!is_array($_SESSION[$local])) {
            $_SESSION[$local] = array();
        }
        if (!isset($_SESSION[$local][$name]) && isset($default)) {
            $_SESSION[$local][$name] = $default;
        }
        return $_SESSION[$local][$name];
    }

    function setLocal($name, $value){
        $local = md5(Session::localName());
        if (!is_array($_SESSION[$local])) {
            $_SESSION[$local] = array();
        }
        $return = $_SESSION[$local][$name];
        if (null === $value) {
            unset($_SESSION[$local][$name]);
        } else {
            $_SESSION[$local][$name] = $value;
        }
        return $return;
    }

    /**
    *  Set new local name
    */
    function localName($name = null){
        $res = @$GLOBALS['__HTTP_Session_Localname'];
        if (!empty($name)) {
            $GLOBALS['__HTTP_Session_Localname'] = $name;
        }
        return $res;
    }

    function  useTransSID($useTransSID = null){
         $res = ini_get('session.use_trans_sid') ? true : false;
         if (isset($useTransSID)) {
             ini_set('session.use_trans_sid', $useTransSID ? 1 : 0);
         }
         return $return;
    }

    /**
    * If optional parameter is specified it detemines the number of seconds after which session
    * data will be seen as 'garbage' and cleaned up
    */
    function setGcMaxLifetime($gcMaxLifetime = null){
        $res = ini_get('session.gc_maxlifetime');
        if (isset($gcMaxLifetime) && is_int($gcMaxLifetime) && $gcMaxLifetime >= 1) {
            ini_set('session.gc_maxlifetime', $gcMaxLifetime);
        }
        return $res;
    }

    /***
    * If optional parameter is specified it determines the probability that the garbage collection routine
    * is started and session data is cleaned up.
    */
    function setGcProbability($gcProbability = null){
        $return = ini_get('session.gc_probability');
        if (isset($gcProbability) && is_int($gcProbability) && $gcProbability >= 1 && $gcProbability <= 100) {
            ini_set('session.gc_probability', $gcProbability);
        }
        return $return;
    }

    /**
    * Tries to find any session id in $_GET, $_POST or $_COOKIE
    */
    function _detectID(){
        if (Session::useCookies()) {
            if (isset($_COOKIE[Session::name()])) {
                return $_COOKIE[Session::name()];
            }
        } else {
            if (isset($_GET[Session::name()])) {
                return $_GET[Session::name()];
            }
            if (isset($_POST[Session::name()])) {
                return $_POST[Session::name()];
            }
        }
        return null;
    } 
}
?>